package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.utils.PinYin4jUtils;

@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class AreaAction extends ActionSupport implements ModelDriven<Area> {
	@Autowired
	private AreaService areaService;
	private Area area = new Area();

	@Override
	public Area getModel() {
		// TODO Auto-generated method stub
		return area;
	}

	private int page;
	private int rows;

	public void setPage(int page) {
		this.page = page;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	private File file;
	private String fileContentType;
	private String fileFileName;

	public void setFile(File file) {
		this.file = file;
	}

	@Action(value = "area_batchImport")
	public String batchImport() {
		List<Area> list = new ArrayList<>();
		try {
			HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));
			HSSFSheet sheet = hwb.getSheetAt(0);

			for (Row r : sheet) {
				if (r.getRowNum() == 0) {
					continue;
				}
				if (r.getCell(0) == null && StringUtils.isBlank(r.getCell(0).getStringCellValue())) {
					continue;
				}
				Area a = new Area();
				a.setId(r.getCell(0).getStringCellValue());
				a.setProvince(r.getCell(1).getStringCellValue());
				a.setCity(r.getCell(2).getStringCellValue());
				a.setDistrict(r.getCell(3).getStringCellValue());
				a.setPostcode(r.getCell(4).getStringCellValue());
				String province = a.getProvince();
				String city = a.getCity();
				String district = a.getDistrict();

				province = province.substring(0, province.length() - 1);
				city = city.substring(0, city.length() - 1);
				district = district.substring(0, district.length() - 1);

				String[] headByString = PinYin4jUtils.getHeadByString(province + city + district);
				StringBuffer sb = new StringBuffer();
				for (String s : headByString) {
					sb.append(s);
				}
				a.setShortcode(sb.toString());
				String hanziToPinyin = PinYin4jUtils.hanziToPinyin(city, "");
				a.setCitycode(hanziToPinyin);
				list.add(a);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		areaService.batchImport(list);
		return NONE;
	}

	@Action(value = "areaFindAll", results = { @Result(name = "success", type = "json") })
	public String areaFindAll() {
		Pageable pa = new PageRequest(page - 1, rows);

		Specification<Area> sf = new Specification<Area>() {

			@Override
			public Predicate toPredicate(Root<Area> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<>();
				if (StringUtils.isNotBlank(area.getProvince())) {
					Predicate predicate = cb.like(root.get("province").as(String.class),
							"%" + area.getProvince() + "%");
					list.add(predicate);
				}
				if (StringUtils.isNotBlank(area.getCity())) {
					Predicate predicate = cb.like(root.get("city").as(String.class), "%" + area.getCity() + "%");
					list.add(predicate);
				}
				if (StringUtils.isNotBlank(area.getDistrict())) {
					Predicate predicate = cb.like(root.get("district").as(String.class),
							"%" + area.getDistrict() + "%");
					list.add(predicate);
				}
				Predicate p = cb.and(list.toArray(new Predicate[0]));
				return p;
			}

		};

		Page<Area> pp = areaService.findAll(sf, pa);
		Map<String, Object> map = new HashMap<>();
		map.put("total", pp.getTotalElements());
		map.put("rows", pp.getContent());
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
}
